package baobaotao.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2015/7/21.
 */
public class PrivateCar {

    private String color;
    protected void drive(){
        System.out.println("drive private car! the color is:"+color);
    }

    public static void main(String[] args) throws Exception{
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("baobaotao.reflect.PrivateCar");
        PrivateCar privateCar = (PrivateCar)clazz.newInstance();
        //获取成员变量
        Field field = clazz.getDeclaredField("color");
        //取消Java语言访问检查以访问private变量
        field.setAccessible(true);
        field.set(privateCar,"红色");

        Method method = clazz.getDeclaredMethod("drive", (Class[]) null);
        //取消Java语言访问检查以访问protected方法
        method.setAccessible(true);
        method.invoke(privateCar,(Object[])null);

    }
}
